import { DataSource } from 'typeorm';
import { Task } from '../../../entities/task.entity';
import { Tag } from '../../../entities/tag.entity';

/**
 * 任务-标签关联表种子数据
 * 负责初始化任务与标签的关联关系
 */
export class TaskTagSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行任务-标签关联种子
   */
  async run(): Promise<void> {
    console.log('开始初始化任务-标签关联数据...');

    const taskRepository = this.dataSource.getRepository(Task);
    const tagRepository = this.dataSource.getRepository(Tag);

    // 查找所有任务
    const tasks = await taskRepository.find();

    if (tasks.length === 0) {
      console.log('未找到任务，跳过任务-标签关联初始化');
      return;
    }

    // 查找所有标签
    const tags = await tagRepository.find();

    if (tags.length === 0) {
      console.log('未找到标签，跳过任务-标签关联初始化');
      return;
    }

    // 一些常用的标签
    const urgentTag = tags.find(tag => tag.name === '紧急');
    const importantTag = tags.find(tag => tag.name === '重要');
    const bugTag = tags.find(tag => tag.name === '缺陷');
    const featureTag = tags.find(tag => tag.name === '功能');
    const improvementTag = tags.find(tag => tag.name === '改进');
    const documentationTag = tags.find(tag => tag.name === '文档');
    const designTag = tags.find(tag => tag.name === '设计');

    // 为每个任务分配相关标签
    for (const task of tasks) {
      let taskTags: Tag[] = [];

      // 根据任务标题分配标签
      const taskTitle = task.title.toLowerCase();
      
      if (taskTitle.includes('需求') || taskTitle.includes('规划')) {
        if (importantTag) taskTags.push(importantTag);
        if (documentationTag) taskTags.push(documentationTag);
      }
      
      if (taskTitle.includes('设计') || taskTitle.includes('界面')) {
        if (designTag) taskTags.push(designTag);
      }
      
      if (taskTitle.includes('开发') || taskTitle.includes('实施')) {
        if (featureTag) taskTags.push(featureTag);
      }
      
      if (taskTitle.includes('测试') || taskTitle.includes('验证')) {
        if (bugTag) taskTags.push(bugTag);
      }
      
      if (taskTitle.includes('部署') || taskTitle.includes('上线')) {
        if (urgentTag) taskTags.push(urgentTag);
        if (importantTag) taskTags.push(importantTag);
      }
      
      // 确保每个任务至少有一个标签
      if (taskTags.length === 0 && improvementTag) {
        taskTags.push(improvementTag);
      }

      // 更新任务的标签（使用关联表）
      if (taskTags.length > 0) {
        // 为每个标签创建任务-标签关联记录
        for (const tag of taskTags) {
          try {
            // 使用原始SQL语句直接插入数据
            await this.dataSource.query(
              `INSERT INTO task_tags(task_id, tag_id) VALUES($1, $2)`,
              [task.id, tag.id]
            );
              
            console.log(`为任务 "${task.title}" 添加标签 "${tag.name}" 成功`);
          } catch (error) {
            console.log(`为任务 "${task.title}" 添加标签 "${tag.name}" 失败: ${error.message}`);
          }
        }
        
        console.log(`为任务 "${task.title}" 分配了 ${taskTags.length} 个标签`);
      }
    }

    console.log('任务-标签关联数据初始化完成');
  }
} 